//
//  MineAccountSetViewController.m
//  ShowYork
//
//  Created by hxh on 2020/8/25.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "MineAccountSetViewController.h"
#import "SLShotViewController.h"
#import "MineFeedbackViewController.h"
#import "DiscoverListViewController.h"
#import "MineAccountUpdateNameViewController.h"
#import "MineAccountSecurityViewController.h"
#import "ChangeNewPhoneViewController.h"
#import "UpdateOldPhoneViewController.h"
#import "MineAccountHeaderView.h"
#import "MineAccountLoginOutCell.h"
#import "MineAccountSetCell.h"
#import "RPPickerView.h"
#import "MinePhotoFooterView.h"
#import "UserInfoModel.h"
#import "ZLPhotoBrowser-Swift.h"
#import "SLImageClipController.h"
@interface MineAccountSetViewController ()<UITableViewDelegate,UITableViewDataSource,MineAccountLoginOutCellDelegate,MineAccountHeaderViewDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)UIView *line;
@property (nonatomic,strong)NSArray *titleArray;
@property (nonatomic,strong)UserInfoModel *userInfo;
@property (nonatomic,strong)MineAccountHeaderView *headerView;
@end

@implementation MineAccountSetViewController

- (NSArray *)titleArray{
    if (!_titleArray) {
        _titleArray = [NSArray array];
    }
    return _titleArray;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
   

    [self findHairlineImageViewUnder:self.navigationController.navigationBar].hidden = YES;
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self findHairlineImageViewUnder:self.navigationController.navigationBar].hidden = NO;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // 初始化数据
    self.titleArray = @[@[@"昵称",@"性别",@"手机号",@"微信帐号",@"QQ帐号"],@[@"关于我们",@"清除缓存"],@[@"隐私与安全"],@[@""]];
    self.userInfo = [UserInfoModel userInfo];
    // 设置UI
    [self setUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateUserInfoPhone) name:@"updatePhone" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateUserInfoIcon) name:@"updateUserInfoIcon" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popToRootViewControllerByRemoteMessage) name:@"popToRootViewControllerByRemoteMessage" object:nil];
    // Do any additional setup after loading the view.
}

- (void)setUI{
    self.navigationItem.title = @"设置";
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.estimatedRowHeight = 100;
    self.tableView.estimatedSectionFooterHeight = .0f;
    self.tableView.estimatedSectionHeaderHeight = .0f;
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.right.equalTo(self.view.mas_right);
        make.left.equalTo(self.view.mas_left);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    
    self.headerView = [[MineAccountHeaderView alloc]init];
    self.headerView.delegate = self;
    
    self.tableView.tableHeaderView = self.headerView;
    
    self.tableView.backgroundColor = RGBA(248, 248, 248, 1);
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.headerView updateUserInfo:self.userInfo];
    
    self.line = [[UIView alloc]init];
    self.line.backgroundColor = RGBA(230, 230, 230, 1);
    [self.view addSubview:self.line];
    [self.line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(0.5);
    }];

}
- (void)updateUserInfoPhone{
    self.userInfo = [UserInfoModel userInfo];
    [self.tableView reloadData];
}
- (void)updateUserInfoIcon{
    self.userInfo = [UserInfoModel userInfo];
    [self.headerView updateUserInfo:self.userInfo];
    [self.tableView reloadData];
    [MobClick event:@"update_userInfo_icon"];
}
- (void)popToRootViewControllerByRemoteMessage{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.titleArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *arr = self.titleArray[section];
    return arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    if (indexPath.section == 3) {
        MineAccountLoginOutCell *cell = [MineAccountLoginOutCell cellWithTableView:tableView];
        cell.delegate = self;
        return cell;
    }
    MineAccountSetCell *cell = [MineAccountSetCell cellWithTableView:tableView];
    NSArray *sourceArray = self.titleArray[indexPath.section];
    [cell setSystemTitle:self.titleArray[indexPath.section][indexPath.row]];
    [cell setSystemContent:@""];
    [cell isHideLine:sourceArray.count-1 == indexPath.row];
    
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:
                [cell setSystemContent:self.userInfo.realName.length == 0?@"未设置":self.userInfo.realName];
                break;
            case 1:{
                NSString *sex = nil;
                if (self.userInfo.sex.intValue == 0) {
                    sex = @"未设置";
                }else if (self.userInfo.sex.intValue == 1){
                    sex = @"男";
                }else if (self.userInfo.sex.intValue == 2){
                    sex = @"女";
                }
                [cell setSystemContent:sex];
            }
                break;
            case 2:{
                NSString *string = [self.userInfo.phone substringWithRange:NSMakeRange(3,4)];
                [cell setSystemContent:[self.userInfo.phone stringByReplacingOccurrencesOfString:string withString:@"****"options:0 range:NSMakeRange(3, 4)]];
            }
                break;
            case 3:
                [cell setSystemContent:self.userInfo.wxOpenId.length == 0?@"未绑定":@"已绑定"];
                break;
            case 4:
                [cell setSystemContent:self.userInfo.qqOpenId.length == 0?@"未绑定":@"已绑定"];
                break;
            default:
                break;
        }
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            [MobClick event:@"user_edit_name_click"];
            
            MineAccountUpdateNameViewController *nameVC = [[MineAccountUpdateNameViewController alloc]init];
            nameVC.oldName = self.userInfo.realName;
            [self.navigationController pushViewController:nameVC animated:YES];
            __weak typeof(self)weakSelf = self;
            nameVC.updateName = ^(NSString * _Nonnull name) {
                __strong typeof(weakSelf)strongSelf = weakSelf;
                strongSelf.userInfo.realName = name;
                [strongSelf.userInfo save];
                [strongSelf.tableView reloadData];
                [strongSelf reloadAccountData];
            };
        }
        if (indexPath.row == 1) {
            
            [MobClick event:@"user_edit_sex_click"];
            
            __weak typeof(self)weakSelf = self;
            RPPickerView *pickView = [[RPPickerView alloc]initWithDataArray:@[@"男",@"女"] andCompleteBlock:^(NSString * _Nonnull content) {
                __strong typeof(weakSelf)strongSelf = weakSelf;
                if (indexPath.row == 1 && content.length != 0) {
                    strongSelf.userInfo.sex = @(2);
                    if ([content isEqualToString:@"男"]) {
                        strongSelf.userInfo.sex = @(1);
                    }
                }
                [strongSelf updateUserInformation];
            }];
            [pickView show];
        }
        if (indexPath.row == 2) {
            UpdateOldPhoneViewController *changePhoneVC = [[UpdateOldPhoneViewController alloc]init];
            UserInfoModel *userInfo = [UserInfoModel userInfo];
            changePhoneVC.phoneStr = userInfo.phone;
            [self.navigationController pushViewController:changePhoneVC animated:YES];
        }
        if (indexPath.row == 3) {
            // 判断是否绑定了
            [self authOtherInformationByType:@0];
        }
        if (indexPath.row == 4) {
            [self authOtherInformationByType:@1];
        }
    }
    
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
            NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
            RPWebViewController *webVC = [[RPWebViewController alloc]init];
            webVC.isDark = NO;
            webVC.webUrl = [NSString stringWithFormat:@"%@user/aboutUs?appVersion=%@&navbar=no",HtmlUrl,app_Version];
            webVC.title = @"关于我们";
            [self.navigationController pushViewController:webVC animated:YES];
        }
        if (indexPath.row == 1) {
            [RPAppManager clearCahceData];
            WKWebsiteDataStore *dateStore = [WKWebsiteDataStore defaultDataStore];
            [dateStore fetchDataRecordsOfTypes:[WKWebsiteDataStore allWebsiteDataTypes] completionHandler:^(NSArray<WKWebsiteDataRecord *> * _Nonnull records) {
                for (WKWebsiteDataRecord *record in records){
                    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:record.dataTypes forDataRecords:@[record] completionHandler:^{
                        
                    }];
                }
            }];
           
            
        }
    }
    if (indexPath.section == 2) {
        MineAccountSecurityViewController *securityVC = [[MineAccountSecurityViewController alloc]init];
        [self.navigationController pushViewController:securityVC animated:YES];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50.0f;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 15.0f;
}
#pragma mark - cellDelegate
- (void)loginOut{
  
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确定退出登录" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alertController dismissViewControllerAnimated:YES completion:nil];
        
        if ([RPAppManager isShowNetworkView]) {
            [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:@"网络好像有点问题，请检查后重试" duration:2 finishHandler:nil];
        }else{
            if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"CLDeviceToken"] length] != 0) {
                [SVProgressHUD show];
                // 删除退出用户
                [UserInfoModel deleteUserInfo];
                NSMutableDictionary *param = [NSMutableDictionary dictionary];
                param[@"md5"] = [RPAppManager md5StrWithApi:UpdateDeviceToken];
                param[@"userId"] = @0;
                param[@"deviceType"] = @2;
                param[@"deviceToken"] = [[NSUserDefaults standardUserDefaults]objectForKey:@"CLDeviceToken"];
                [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(UpdateDeviceToken) parames:param success:^(id responseObj) {
                    [SVProgressHUD dismiss];
 
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"removeTimer" object:nil];
                    
                    DiscoverListViewController *listVC = [[DiscoverListViewController alloc]init];
                    NavigationViewController *nav = [[NavigationViewController alloc]initWithRootViewController:listVC];
                    [UIApplication sharedApplication].keyWindow.rootViewController = nav;

                } failure:^(id error) {
                                
                }];
            }else{
                [UserInfoModel deleteUserInfo];
               
                [[NSNotificationCenter defaultCenter] postNotificationName:@"removeTimer" object:nil];
                
                DiscoverListViewController *listVC = [[DiscoverListViewController alloc]init];
                NavigationViewController *nav = [[NavigationViewController alloc]initWithRootViewController:listVC];
                [UIApplication sharedApplication].keyWindow.rootViewController = nav;

                
//                TabBarViewController *tabVC = [[TabBarViewController alloc]init];
//                [UIApplication sharedApplication].keyWindow.rootViewController = tabVC;
                
                

            }
        }
    }];

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alertController dismissViewControllerAnimated:YES completion:nil];
    }];


    [cancelAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
    [confirmAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
       
    //往alertViewController上添加alertAction
    [alertController addAction:confirmAction];
    [alertController addAction:cancelAction];

    [self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark - 修改用户信息
- (void)updateUserInformation{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if (self.userInfo.userLevel.intValue > 0) {
        param[@"userLevel"] = self.userInfo.userLevel;
    }
    param[@"id"] = self.userInfo.id;
    param[@"sex"] = self.userInfo.sex;
    param[@"imagePath"] = self.userInfo.imagePath;
    param[@"realname"] = self.userInfo.realName;
    param[@"userSign"] = self.userInfo.userSign;
    param[@"md5"] = [RPAppManager md5StrWithApi:UpdateUserInfo];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(UpdateUserInfo) parames:param success:^(id responseObj) {
        [self.userInfo save];
        
        [self reloadAccountData];
        // 更新头部视图
        [self.headerView updateUserInfo:self.userInfo];
        
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}
#pragma mark - MineAccountHeaderViewDelegate
- (void)updateHeaderInfoIcon{
    //
    __weak typeof(self)weakSelf = self;
    MinePhotoFooterView *footerView = [[MinePhotoFooterView alloc]initWithCompleteBlock:^(NSInteger index) {
        if (index == 2) {
            __weak typeof(self)weakSelf = self;
            NSInteger index = 1;
            [ZLPhotoConfiguration default].maxSelectCount = index;
            [ZLPhotoConfiguration default].allowSelectImage = true;
            [ZLPhotoConfiguration default].enablePhotoClip = true;
            [ZLPhotoConfiguration default].allowTakePhoto = false;
            [ZLPhotoConfiguration default].allowSelectVideo = false;
            [ZLPhotoConfiguration default].showSelectBtnWhenSingleSelect = false;
            [ZLPhotoConfiguration default].allowPreviewVideo = false;
            [ZLPhotoConfiguration default].allowTakePhotoInLibrary = false;
            [ZLPhotoConfiguration default].enableBottomToolViewCropView = false;
            [ZLPhotoConfiguration default].themeColorDeploy.bottomToolViewBgColor = RGBA(21, 24, 35, 1);
            [ZLPhotoConfiguration default].themeColorDeploy.navBarColor = RGBA(21, 24, 35, 1);
            [ZLPhotoConfiguration default].themeColorDeploy.albumListBgColor = RGBA(21, 24, 35, 1);
            [ZLPhotoConfiguration default].themeColorDeploy.thumbnailBgColor = RGBA(21, 24, 35, 1);
            [ZLPhotoConfiguration default].themeColorDeploy.navEmbedTitleViewBgColor = [UIColor clearColor];
            [ZLPhotoConfiguration default].customImageNames = @[@"zl_retake",@"zl_albumSelect",@"zl_downArrow",@"zl_btn_selected",@"zl_btn_unselected",@"zl_video"];

            [ZLPhotoConfiguration default].navTitleFont = [UIFont boldSystemFontOfSize:16];

            [ZLPhotoConfiguration default].languageType = ZLLanguageTypeChineseSimplified;
            [ZLPhotoConfiguration default].showVideoHud = false;
            [ZLPhotoConfiguration default].previewImageBlock = ^{
                [MobClick event:@"album_image_preview_click"];
            };
            ////            如果allowTakePhoto和allowRecordVideo均为false，则不会显示
            ZLPhotoPreviewSheet *sheet = [[ZLPhotoPreviewSheet alloc]initWithSelectedAssets:@[]];


            [ZLPhotoConfiguration default].clipImageBlock = ^(UIImage * _Nonnull image, UIViewController * _Nonnull parentVC) {

                SLImageClipController * clipVC = [[SLImageClipController alloc]init];
                clipVC.image = image;
                clipVC.modalPresentationStyle = UIModalPresentationFullScreen;

                [parentVC presentViewController:clipVC animated:YES completion:nil];
            };
            [sheet showPhotoLibraryWithSender:weakSelf];
        }
        if (index == 1) {
            SLShotViewController *videoVC = [[SLShotViewController alloc]initWithShotType:@1 onlyPhoto:YES];
            videoVC.modalPresentationStyle = UIModalPresentationFullScreen;
            [weakSelf presentViewController:videoVC animated:YES completion:nil];
        }
    }];
    [footerView show];
}
#pragma mark - 刷新上层页面的数据显示
- (void)reloadAccountData{
    if (self.refresh) {
        self.refresh();
    }
}
#pragma mark - 绑定三方信息
- (void)authOtherInformationByType:(NSNumber *)type{
    __weak typeof(self)weakSelf = self;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"DDup 想要打开%@",type.intValue == 0?@"微信":@"QQ"] message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alertController dismissViewControllerAnimated:YES completion:nil];
    }];

    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"打开" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alertController dismissViewControllerAnimated:YES completion:nil];
        
        UMSocialPlatformType platformType = type.intValue == 0?UMSocialPlatformType_WechatSession:UMSocialPlatformType_QQ;
        [[UMSocialManager defaultManager] getUserInfoWithPlatform:platformType currentViewController:nil completion:^(id result, NSError *error) {
            if (error == nil) {
                
                UMSocialUserInfoResponse *resp = result;
                NSMutableDictionary *param = [NSMutableDictionary dictionary];
                param[@"md5"] = [RPAppManager md5StrWithApi:UpdateOpenId];
                param[@"id"] = [RPAppManager getCustomerId];
                param[@"type"] = type.intValue == 0?@1:@2;
                param[@"openId"] = resp.openid;
                [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(UpdateOpenId) parames:param success:^(id responseObj) {
                    [weakSelf getUserInfoById:[RPAppManager getCustomerId]];
                    
                    
                    if (type.intValue == 0) {
                        [MobClick event:@"user_bind_wechat"];
                    }else{
                        [MobClick event:@"user_bind_qq"];
                    }
                    
                } failure:^(NSError *error) {
                    [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
                }];
                
            }
        }];
        
    }];
    [confirmAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
    [cancelAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
             //往alertViewController上添加alertAction
    [alertController addAction:cancelAction];
    [alertController addAction:confirmAction];
  
    [self presentViewController:alertController animated:YES completion:nil];
    
    

}

- (void)getUserInfoById:(NSNumber *)userId{
    // 请求用户登录信息
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = userId;
    param[@"md5"] = [RPAppManager md5StrWithApi:GetUser];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetUser) parames:param success:^(id responseObj) {

        UserInfoModel *userInfo = [UserInfoModel mj_objectWithKeyValues:responseObj[RESPONSE]];
        [userInfo save];
        
        self.userInfo = userInfo;
    
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_success"] message:@"绑定成功" duration:2 finishHandler:nil];
        
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    
    }];
}

- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

@end
